package com.meiyu.live.ui.main;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.meiyu.live.BaseFragment;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.net.FileReqPackage;
import com.meiyu.live.net.UploadFile;
import com.meiyu.live.net.callback.UploadCallBack;
import com.meiyu.live.net.param.CreateLiveRoomParams;
import com.meiyu.live.net.param.UploadFileParams;
import com.meiyu.live.net.response.CreateRooomResponse;
import com.meiyu.live.net.response.UploadResponse;
import com.meiyu.live.tv.anchor.AnchorActivity;
import com.meiyu.live.util.BitmapUtil;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import vn.tungdx.mediapicker.MediaItem;
import vn.tungdx.mediapicker.MediaOptions;
import vn.tungdx.mediapicker.activities.MediaPickerActivity;

import static android.app.Activity.RESULT_OK;
import static vn.tungdx.mediapicker.activities.MediaPickerActivity.EXTRA_MEDIA_OPTIONS;

/**
 * 正在热播
 */
public class StartLiveFragment extends BaseFragment implements View.OnClickListener {
    private ImageView iv_avator, iv_qq, iv_wechat, iv_wxpy, iv_qzone, iv_sina;
    private TextView tv_next, tv_yx, tv_yl, tv_hw, tv_ty, tv_jr;
    private EditText et_description;
    private View choose_share, choose_category, ll_avator;
    private NetLoadingDailog dialog_loading;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private int hook_status;
    private static final int REQUEST_MEDIA = 100;
    private MediaItem imgUrl;
    private CreateRooomResponse response;

    Map<Integer, SHARE_MEDIA> share_mediaMap = new HashMap<Integer, SHARE_MEDIA>();

    public static StartLiveFragment newInstance(int hook_status) {
        StartLiveFragment fragment = new StartLiveFragment();
        fragment.setHook_status(hook_status);
        return fragment;
    }

    public void setHook_status(int hook_status) {
        this.hook_status = hook_status;
    }

    @Override
    public int getContextView() {
        return R.layout.fragment_startlive;
    }

    @Override
    protected void init() {
        dialog_loading = new NetLoadingDailog(getActivity());
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();

        share_mediaMap.put(R.id.iv_qq, SHARE_MEDIA.QQ);
        share_mediaMap.put(R.id.iv_wechat, SHARE_MEDIA.WEIXIN);
        share_mediaMap.put(R.id.iv_wxpy, SHARE_MEDIA.WEIXIN_CIRCLE);
        share_mediaMap.put(R.id.iv_sina, SHARE_MEDIA.SINA);
        share_mediaMap.put(R.id.iv_qzone, SHARE_MEDIA.QZONE);
        et_description = (EditText) findViewById(R.id.et_description);
        iv_avator = (ImageView) findViewById(R.id.avator);
        iv_qq = (ImageView) findViewById(R.id.iv_qq);
        iv_wechat = (ImageView) findViewById(R.id.iv_wechat);
        iv_wxpy = (ImageView) findViewById(R.id.iv_wxpy);
        iv_qzone = (ImageView) findViewById(R.id.iv_qzone);
        iv_sina = (ImageView) findViewById(R.id.iv_sina);
        iv_qq.setOnClickListener(this);
        iv_wechat.setOnClickListener(this);
        iv_wxpy.setOnClickListener(this);
        iv_qzone.setOnClickListener(this);
        iv_sina.setOnClickListener(this);

        iv_qq.setTag(R.id.tag_default, R.drawable.qq_default);
        iv_qq.setTag(R.id.tag_sel, R.drawable.qq_sel);
        iv_qq.setTag(R.id.tag_status, 0);
        iv_wechat.setTag(R.id.tag_default, R.drawable.wechat_default);
        iv_wechat.setTag(R.id.tag_sel, R.drawable.wechat_sel);
        iv_wechat.setTag(R.id.tag_status, 0);
        iv_wxpy.setTag(R.id.tag_default, R.drawable.wxpy);
        iv_wxpy.setTag(R.id.tag_sel, R.drawable.wxpy_sel);
        iv_wxpy.setTag(R.id.tag_status, 0);
        iv_qzone.setTag(R.id.tag_default, R.drawable.qzone_default);
        iv_qzone.setTag(R.id.tag_sel, R.drawable.qzone_sel);
        iv_qzone.setTag(R.id.tag_status, 0);
        iv_sina.setTag(R.id.tag_default, R.drawable.sina_default);
        iv_sina.setTag(R.id.tag_sel, R.drawable.sina_sel);
        iv_sina.setTag(R.id.tag_status, 0);

        ll_avator = findViewById(R.id.ll_avator);
        ll_avator.setOnClickListener(this);

        tv_yx = (TextView) findViewById(R.id.tv_yx);
        tv_yl = (TextView) findViewById(R.id.tv_yl);
        tv_hw = (TextView) findViewById(R.id.tv_hw);
        tv_ty = (TextView) findViewById(R.id.tv_ty);
        tv_jr = (TextView) findViewById(R.id.tv_jr);

        tv_yx.setTag(R.id.tag_category_id, 1);
        tv_yl.setTag(R.id.tag_category_id, 3);
        tv_hw.setTag(R.id.tag_category_id, 5);
        tv_ty.setTag(R.id.tag_category_id, 9);
        tv_jr.setTag(R.id.tag_category_id, 10);

        tv_yx.setOnClickListener(this);
        tv_yl.setOnClickListener(this);
        tv_hw.setOnClickListener(this);
        tv_ty.setOnClickListener(this);
        tv_jr.setOnClickListener(this);

        tv_next = (TextView) findViewById(R.id.btn_next);
        tv_next.setOnClickListener(this);
        getData();
    }


    private void changeStyleForCategory(View view) {
        if (choose_category != null && choose_category.getId() == view.getId() && (int) view.getTag(R.id.tag_status) == 1) {
            view.setBackgroundResource(R.drawable.hui);
            ((TextView) view).setTextColor(getResources().getColor(R.color.action_bar_txt_color));
            choose_category = null;
        } else {
            if (choose_category != null) {
                choose_category.setBackgroundResource(R.drawable.hui);
                ((TextView) choose_category).setTextColor(getResources().getColor(R.color.action_bar_txt_color));
                view.setTag(R.id.tag_status, 0);
            }
            view.setBackgroundResource(R.drawable.blue);
            ((TextView) view).setTextColor(getResources().getColor(R.color.main_theme_color));
            view.setTag(R.id.tag_status, 1);
            choose_category = view;
        }
    }

    private void changeStyleForShare(View view) {
        if (choose_share != null && choose_share.getId() == view.getId() && (int) view.getTag(R.id.tag_status) == 1) {
            ((ImageView) view).setImageResource((int) view.getTag(R.id.tag_default));
            choose_share = null;
        } else {
            if (choose_share != null) {
                ((ImageView) choose_share).setImageResource((int) choose_share.getTag(R.id.tag_default));
                view.setTag(R.id.tag_status, 0);
            }
            ((ImageView) view).setImageResource((int) view.getTag(R.id.tag_sel));
            view.setTag(R.id.tag_status, 1);
            choose_share = view;
        }
    }

    private void getData() {
        imageLoader.displayImage(UserConfig.getInstance().getPersonalInfo().getAvatar(), iv_avator, options);

    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        super.onErrorResponse(volleyError);
    }

    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            //跳转到直播界面之前要释放摄像头
            Toast.makeText(getActivity(), "分享成功", Toast.LENGTH_SHORT).show();
            AnchorActivity.start(getActivity(), response);
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getActivity(), "分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            Toast.makeText(getActivity(), "分享取消", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MEDIA) {
            if (resultCode == RESULT_OK) {
                List<MediaItem> mMediaSelectedList = MediaPickerActivity
                        .getMediaItemSelected(data);
                if (mMediaSelectedList != null) {
                    for (MediaItem mediaItem : mMediaSelectedList) {
                        imgUrl = mediaItem;
                        imageLoader.displayImage(imgUrl.getUriOrigin().toString(), iv_avator, options);
                    }
                }
            }
        }
    }

    UploadCallBack callBack = new UploadCallBack() {
        @Override
        public void response(UploadResponse response) {
            if (response.getCode() == 200) {
                jump();
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog_loading.dismissDialog();
                        ToastUtil.show("图片上传失败");
                    }
                });
            }

        }
    };

    private void jump() {
//        UMImage image = new UMImage(getActivity(), UserConfig.getInstance().getPersonalInfo().getAvatar());
//        new ShareAction(getActivity())
//                .setPlatform(SHARE_MEDIA.WEIXIN)
//                .setCallback(umShareListener)
//                .withTitle(UserConfig.getInstance().getPersonalInfo().getName() + "正在直播，快来支持一下吧！")
//                .withTargetUrl("http://mt.201.0110net.com/m/live.html?u=")
//                .withMedia(image)
//                .share();
        final CreateLiveRoomParams createLiveRoomParams = new CreateLiveRoomParams(et_description.getText().toString(), (int) choose_category.getTag(R.id.tag_category_id));
        request(createLiveRoomParams, CreateRooomResponse.class, new Response.Listener<CreateRooomResponse>() {
            @Override
            public void onResponse(CreateRooomResponse createRooomResponse) {
                if (createRooomResponse.getStatusCode() == Constant.StatusCode_Success) {
                    response = createRooomResponse;
                    if (choose_share != null) {
                        share_mediaMap.get(choose_share.getId());
                        UMImage image;
                        if (imgUrl != null) {
                            image = new UMImage(getActivity(), BitmapFactory.decodeFile(imgUrl.getPathOrigin(getActivity())));
                        } else {
                            image = new UMImage(getActivity(), UserConfig.getInstance().getPersonalInfo().getAvatar());
                        }
                        new ShareAction(getActivity())
                                .setPlatform(share_mediaMap.get(choose_share.getId()))
                                .setCallback(umShareListener)
                                .withTitle(UserConfig.getInstance().getPersonalInfo().getName() + "正在直播，快来支持一下吧！")
                                .withText(createLiveRoomParams.getDescription())
                                .withTargetUrl("http://mt.201.0110net.com/m/live.html?u=" + createRooomResponse.getUnique_id() + "&s=" + createRooomResponse.getHookup_screening_id())
                                .withMedia(image)
                                .share();
                    } else {
                        //跳转到直播界面之前要释放摄像头
                        AnchorActivity.start(getActivity(), createRooomResponse);
                    }
//                    } //跳转到直播界面之前要释放摄像头
//                    AnchorActivity.start(getActivity(), createRooomResponse);
//                    getActivity().finish();
                } else {
                    ToastUtil.show(createRooomResponse.getMsg());
                }
                dialog_loading.dismissDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_avator:
                MediaOptions options = MediaOptions.createDefault();
                Intent intent = new Intent(getActivity(), MediaPickerActivity.class);
                intent.putExtra(EXTRA_MEDIA_OPTIONS, options);
                startActivityForResult(intent, REQUEST_MEDIA);
                break;
            case R.id.tv_yx:
            case R.id.tv_yl:
            case R.id.tv_hw:
            case R.id.tv_ty:
            case R.id.tv_jr:
                changeStyleForCategory(v);
                break;
            case R.id.iv_qq:
            case R.id.iv_wechat:
            case R.id.iv_wxpy:
            case R.id.iv_sina:
            case R.id.iv_qzone:
                changeStyleForShare(v);
                break;
            case R.id.btn_next:
                if (hook_status != 0) {
                    ToastUtil.show("直播异常结束，请一分钟后再试。");
                } else if (TextUtils.isEmpty(et_description.getText().toString())) {
                    ToastUtil.show("请填写描述");
                } else if (choose_category == null) {
                    ToastUtil.show("请选择分类");
                } else if (TextUtils.isEmpty(UserConfig.getInstance().getPersonalInfo().getAvatar()) && imgUrl == null) {
                    ToastUtil.show("请上传图片");
                } else {
                    dialog_loading.loading();

                    String body = new FileReqPackage(new UploadFileParams("video_pic")).packetParam();
                    if (imgUrl != null) {
                        new Thread(new UploadFile(
                                Constant.URL + Constant.UrlParams.UPLOAD,
                                BitmapUtil.compressImage(imgUrl.getPathOrigin(getActivity())), new File(imgUrl.getPathOrigin(getActivity())).getName(),
                                body,
                                callBack)).start();
                    } else {
                        jump();
                    }

                }
                break;
        }
    }
}
